import {
  View,
  Text,
  Picker,
  ScrollView,
  Image,
  Button,
  Textarea,
} from "@tarojs/components";
import { useEffect, useState } from "react";
import Taro from "@tarojs/taro";
import { isEmpty } from "lodash-es";
import {
  useMemoizedFn,
  useRequest,
  useBoolean,
  useCounter,
  useMount,
} from "ahooks";
import { getLevelConfig, getPayLevelConfig, ali_vip_pay } from "@/api";
import { HtmlView } from "@/components/taro-html-view";

import "./index.module.scss";

interface Props {
  defaultShow?: boolean;
  show?: boolean;
  showClose?: () => void;
  onSuccess?: () => void;
}

export default function PayLevelConfin({
  defaultShow,
  show,
  showClose,
  onSuccess,
}: Props) {
  const [showLevel, { setFalse, setTrue }] = useBoolean(false);
  const [showLevelConfrim, { setFalse: closeConfrim, setTrue: openConfrim }] =
    useBoolean(false);
  const [redayTime, { dec, reset }] = useCounter(5);
  const [memo, setMemo] = useState("");

  const [signedData, setSignedData] = useState({
    asset_id: "",
    url: "",
    key: "",
  });

  const { run, data: levelConfig } = useRequest(getLevelConfig, {
    manual: true,
    onSuccess() {
      setTimeout(() => {
        setTrue();
      }, 100);
    },
  });

  const { runAsync: payLevelConfig } = useRequest(getPayLevelConfig, {
    manual: true,
  });

  useMount(() => {
    if (defaultShow) {
      run();
    }
  });

  const handleRunLevel = useMemoizedFn(() => {
    if (show) {
      run();
      showClose?.();
    }
  });

  useEffect(() => {
    show && handleRunLevel();

    Taro.eventCenter.on("signed", (res) => {
      // console.log(res);
      setSignedData(res);
    });
  }, [handleRunLevel, show]);

  const handlePayLevel = useMemoizedFn(async () => {
    if (!signedData.asset_id) {
      Taro.showToast({ title: "请先阅读协议并签名", icon: "none" });
      return false;
    }
    try {
      Taro.showLoading();
      var userAgent = navigator.userAgent.toLowerCase();

      if (
        levelConfig.pay_mode == 1 &&
        userAgent.indexOf("micromessenger") !== -1
      ) {
        // 微信支付
        const { pay_data: payParams } = await payLevelConfig({
          plan_id: levelConfig?.id,
          sign_file: signedData.asset_id,
          memo,
          is_wx: 1,
        });
        console.log("payParams", payParams);
        if (isEmpty(payParams)) throw "升级失败";
        payParams["provider"] = "wxpay";
        payParams["success"] = () => {
          Taro.showToast({ title: "升级成功" });
          setFalse();
          onSuccess?.();
        };
        payParams["fail"] = () => {
          Taro.showToast({ title: "升级失败", icon: "none" });
        };

        // Taro.requestPayment(payParams);
        if (typeof WeixinJSBridge === "undefined") {
          // 在非微信浏览器中，WeixinJSBridge是undefined
          return;
        }
        // 调起微信支付
        WeixinJSBridge.invoke(
          "getBrandWCPayRequest",
          {
            appId: payParams.appId,
            timeStamp: payParams.timeStamp,
            nonceStr: payParams.nonceStr,
            package: payParams.package,
            signType: payParams.signType,
            paySign: payParams.paySign,
          },
          function (res) {
            console.log("res", res);
            if (res.err_msg === "get_brand_wcpay_request:ok") {
              Taro.showToast({ title: "支付成功！", icon: "none" });
              closeConfrim();
            } else {
              // 支付失败处理
              Taro.showModal({
                title: "支付失败",
                content: "请重新尝试支付",
                showCancel: false,
              });
            }
          }
        );
      } else {
        // 支付宝支付
        ali_vip_pay({
          plan_id: levelConfig?.id,
          sign_file: signedData.asset_id,
          memo,
        }).then((res) => {
          console.log("支付宝支付", Taro.getStorageSync("userInfo")?.token);
          // window.location.href = res.data.ali_pay_url
          Taro.navigateTo({
            url:
              "/pages/alipay/index?order_no=" +
              res.data.order_no +
              "&token=" +
              Taro.getStorageSync("userInfo")?.token,
          });
        });
      }
    } catch (error) {
      Taro.showToast({
        title: "升级失败",
        icon: "none",
      });
    } finally {
      Taro.hideLoading();
    }
  });

  const openConfirmModal = useMemoizedFn(() => {
    openConfrim();
    reset();
    setMemo("");
    setFalse();
    const redeyTimer = setInterval(() => {
      if (redayTime <= 0) {
        clearInterval(redeyTimer);
      }
      dec();
    }, 1000);
  });

  const goSign = async () => {
    Taro.navigateTo({
      url: "/pages/mine/vipam",
    });
  };

  return (
    <View className="pay-level-modal-box">
      <View
        className={`cu-modal ${showLevel ? "show" : ""}`}
        onClick={setFalse}
      >
        <View className="cu-dialog" onClick={(e) => e?.stopPropagation()}>
          <View className="padding-tb text-gl text-bold">
            升级成为 VIP 代理商
          </View>
          <View className="level-box">
            <HtmlView
              previewImage
              className="level-html"
              html={levelConfig?.body || ""}
            />
          </View>
          <View className="flex align-center justify-around">
            <View
              onClick={setFalse}
              className="flex-sub text-dl solid text-center margin nav round  padding-tb-sm"
            >
              &emsp;取消&emsp;
            </View>
            <View
              onClick={openConfirmModal}
              className="main-bc main-borderc flex-sub whitespace-nowrap nav text-dl text-center margin padding-tb-sm round line-white"
            >
              &emsp;立即升级&emsp;
            </View>
          </View>
        </View>
      </View>
      <View
        className={`cu-modal bottom-modal ${showLevelConfrim ? "show" : ""}`}
        onClick={closeConfrim}
      >
        <View
          className="cu-dialog"
          style={{ paddingBottom: "60px" }}
          onClick={(e) => e?.stopPropagation()}
        >
          <View className="cu-bar bg-white">
            <View className="action" />
            <View className="padding-tb text-gl text-bold">VIP 代理商协议</View>
            <View className="action" onClick={closeConfrim}>
              取消
            </View>
          </View>
          <View className="level-confrim-box">
            <HtmlView
              previewImage
              className="level-confrim-html"
              html={levelConfig?.agreement || ""}
            />
          </View>
          <View className="flex flex-direction align-center padding-bottom justify-around">
            <View className="w-100 agree-sec" onClick={goSign}>
              <Text
                className={
                  signedData.asset_id ? "cuIcon-roundcheckfill" : "cuIcon-round"
                }
              ></Text>{" "}
              已阅读本协议并签名
            </View>
            <View className=" w-100 padding-lr">
              <Button
                // disabled={!(redayTime <= 0)}
                disabled={!signedData.asset_id}
                onClick={handlePayLevel}
                className="main-bc padding-tb-xs whitespace-nowrap nav text-dl text-center round line-white"
              >
                {/* &emsp;同意协议并开通代理{redayTime > 0 ? `(${redayTime}s)` : ''}&emsp; */}
                &emsp;开通VIP代理商&emsp;
              </Button>
            </View>
          </View>
        </View>
      </View>
    </View>
  );
}
